package com.ruoyi.thirdpart.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.service.IEmployeeUserService;
import com.ruoyi.market.domain.ConfigProgram;
import com.ruoyi.market.domain.ConfigMessage;
import com.ruoyi.market.service.IConfigProgramService;
import com.ruoyi.market.service.IConfigMessageService;
import com.ruoyi.order.domain.OrderGift;
import com.ruoyi.order.domain.OrderGoods;
import com.ruoyi.order.service.IOrderGiftService;
import com.ruoyi.order.service.IOrderGoodsService;
import com.ruoyi.thirdpart.domain.WeChatTemplate;
import com.ruoyi.thirdpart.domain.WeiXinResponse;
import com.ruoyi.thirdpart.service.IWxOAuthchatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 模板通知 业务层处理
 *
 * @author ruoyi
 */
@Service
@Component
public class WxOAuthServiceImpl implements IWxOAuthchatService
{

    // 令牌有效期（默认120分钟）
    @Value("${token.expireTimeOfWxAccessToken}")
    private int expireTimeOfWxAccessToken;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private IConfigMessageService configMessageService;

    @Autowired
    private IConfigProgramService configProgramService;

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private IEmployeeUserService employeeUserService;

    @Autowired
    private IOrderGoodsService orderGoodsService;

    @Autowired
    private IOrderGiftService orderGiftService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void sendMessage(String wxAccessToken) {
        WeChatTemplate weChatTemplate = new WeChatTemplate();

        // 设置模板id
        weChatTemplate.setTemplateId("5Ag_P7K_C-iPV_EEurcSDhbanPV2VFBO4OuT0dMALdg");

        // 设置接收用户openId，这里填接收者的openid
        weChatTemplate.setToUser("owte76Js8GeSNNpUBqXy9GFxCXNM");

        //点击详情跳转的地址
        weChatTemplate.setUrl("");

        /**
         * 设置模板data参数
         * {{keyword1.DATA}}
         */
        weChatTemplate.getData().put("time3", WeChatTemplate.initData("2022-10-23 14:23:26","#459ae9"));//申请时间
        weChatTemplate.getData().put("thing1", WeChatTemplate.initData("张三","#459ae9"));//客户姓名
        weChatTemplate.getData().put("remark", WeChatTemplate.initData("如遇错误，请往当地社区服务中心进行解决。感谢您的使用！","#383838"));


        if(wxAccessToken != null){
            // 发送消息的接口
            String pust_message_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

            //调用微信接口，发送模板消息
            WeiXinResponse result = restTemplate.postForObject(String.format(pust_message_url, wxAccessToken),
                    weChatTemplate, WeiXinResponse.class);
            if (result.getErrcode() == 0){;
                System.out.println("========== 模板消息发送成功 ======== ");
            }else{
                System.out.println("========== 模板消息发送失败 ======");
            }
        }else{
            System.out.println("========== 模板消息失败 ==========");
        }
    }

    /**
     * 获取getAccessToken
     * @return
     */
    public String getAccessToken(String shopId) {
        try {
            String userKey = getCacheKey("wx.access.token.expireTime");
            String access_token = redisCache.getCacheObject(userKey);
            // 从缓存中取token
            if(access_token != null){
                System.out.println("=====获取redis access_token的结果为========"+access_token+"=============");
                return access_token;
            }
            ConfigProgram configProgram = configProgramService.selectConfigProgramByShopId(shopId);
            // String appid = "wxedf369ca63e9cfa6";//填写公众号的appid
            // String secret = "a5e0b68b125ea7774b92ed5f330ceb0a";//填写公众号的开发者密码(AppSecret)
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+configProgram.getOfficialAppId()+"&secret="+configProgram.getOfficialSecret();

            System.out.println("=====获取微信token的url为========"+url+"=============");
            StringBuilder json = new StringBuilder();
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            JSONObject object = (JSONObject) JSONObject.parse(String.valueOf(json));

            access_token = object.getString("access_token");
            if (access_token != null) {
                System.out.println("=====获取微信access_token的结果为========"+access_token+"=============");

                // 缓存accesstoken 有效期 2小时 = 120分钟 = 7200秒
                redisCache.setCacheObject(userKey, access_token, expireTimeOfWxAccessToken, TimeUnit.MINUTES);

                return access_token;
            } else {
                String errcode = object.getString("errcode");
                String errmsg = object.getString("errmsg");
                System.out.println("=====获取微信 getAccessToken errcode的结果为========"+errcode+"=============");
                System.out.println("=====获取微信 getAccessToken errmsg的结果为========"+errmsg+"=============");
            }
            return null;
        } catch (Exception e) {
            System.out.println("获取微信accessToken异常:" + e.getMessage());
            return null;
        }
    }

    // 订单支付成功通知
    // 消费项目
    // {{thing9.DATA}}
    // 消费金额
    // {{amount1.DATA}}
    // 客户名称
    // {{thing28.DATA}}
    // 消费时间
    // {{time3.DATA}}
    // 订单编号
    // {{character_string12.DATA}}
    public void messageReward(String orderNo){

        OrderGift orderGift = orderGiftService.selectOrderGiftByOrderNo(orderNo);

        CustomerUser customerUser = customerUserService.selectUserById(orderGift.getOrderUserId());

        EmployeeUser employeeUser = employeeUserService.selectUserById(orderGift.getEmployeeUserId());

        ConfigMessage sysConfigMessage = configMessageService.selectConfigMessageByShopId(orderGift.getShopId());

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(orderGift.getCreateTime());

        WeChatTemplate weChatTemplate = new WeChatTemplate();

        // 设置模板id
        weChatTemplate.setTemplateId(sysConfigMessage.getWxOaPaySuccessId());

        //点击详情跳转的地址
        weChatTemplate.setUrl("");

        weChatTemplate.getData().put("thing28", WeChatTemplate.initData(customerUser.getNickName(),"#459ae9")); // 客户姓名
        weChatTemplate.getData().put("character_string12", WeChatTemplate.initData(orderNo,"#459ae9"));    // 订单号
        weChatTemplate.getData().put("time3", WeChatTemplate.initData(dateStr,"#459ae9"));    // 消费时间
        weChatTemplate.getData().put("thing9", WeChatTemplate.initData("客户打赏","#459ae9"));    // 消费项目
        weChatTemplate.getData().put("amount1", WeChatTemplate.initData(orderGift.getActualAmount().toString(),"#459ae9"));    // 消费金额

        // 设置接收用户openId，这里填接收者的openid -- 下单用户
        if(customerUser.getOpenId() != null && !customerUser.getOpenId().equals("")){
            weChatTemplate.setToUser(customerUser.getOpenId());
            messageCenter(weChatTemplate, orderGift.getShopId());
        }

        // 设置接收用户openId，这里填接收者的openid -- 店员(指定店员)
        if(employeeUser != null && employeeUser.getOpenId() != null && !employeeUser.getOpenId().equals("")){
            weChatTemplate.setToUser(employeeUser.getOpenId());
            messageCenter(weChatTemplate, orderGift.getShopId());
        }
    }

    // 订单支付成功通知
    // 消费项目
    // {{thing9.DATA}}
    // 消费金额
    // {{amount1.DATA}}
    // 客户名称
    // {{thing28.DATA}}
    // 消费时间
    // {{time3.DATA}}
    // 订单编号
    // {{character_string12.DATA}}
    public void messageOrderPaySuccess(String orderNo){

        OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(orderNo);

        CustomerUser customerUser = customerUserService.selectUserById(orderGoods.getOrderUserId());

        EmployeeUser employeeUser = employeeUserService.selectUserById(orderGoods.getEmployeeUserId());

        WeChatTemplate weChatTemplate = new WeChatTemplate();

        ConfigMessage sysConfigMessage = configMessageService.selectConfigMessageByShopId(orderGoods.getShopId());

        // 设置模板id
        weChatTemplate.setTemplateId(sysConfigMessage.getWxOaPaySuccessId());

        //点击详情跳转的地址
        weChatTemplate.setUrl("");

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(orderGoods.getCreateTime());

        weChatTemplate.getData().put("thing28", WeChatTemplate.initData(customerUser.getNickName(),"#459ae9")); // 客户姓名
        weChatTemplate.getData().put("character_string12", WeChatTemplate.initData(orderNo,"#459ae9"));    // 订单号
        weChatTemplate.getData().put("time3", WeChatTemplate.initData(dateStr,"#459ae9"));    // 消费时间
        weChatTemplate.getData().put("thing9", WeChatTemplate.initData("客户下单","#459ae9"));    // 消费项目
        weChatTemplate.getData().put("amount1", WeChatTemplate.initData(orderGoods.getActualAmount().toString(),"#459ae9"));    // 消费金额

        // 设置接收用户openId，这里填接收者的openid -- 下单用户
        if(customerUser.getOpenId() != null && !customerUser.getOpenId().equals("")){
            weChatTemplate.setToUser(customerUser.getOpenId());
            messageCenter(weChatTemplate, orderGoods.getShopId());
        }

        // 设置接收用户openId，这里填接收者的openid -- 店员(指定店员)
        if(employeeUser != null && employeeUser.getOpenId() != null && !employeeUser.getOpenId().equals("")){
            weChatTemplate.setToUser(employeeUser.getOpenId());
            messageCenter(weChatTemplate, orderGoods.getShopId());
        }
    }

    // 订单已超时提醒
    // 预定客户
    // {{thing12.DATA}}
    // 订单金额
    // {{amount4.DATA}}
    // 下单时间
    // {{time3.DATA}}
    // 订单号
    // {{character_string1.DATA}}
    public void messageOrderOvertime(String orderNo){

        OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(orderNo);

        CustomerUser customerUser = customerUserService.selectUserById(orderGoods.getOrderUserId());

        EmployeeUser employeeUser = employeeUserService.selectUserById(orderGoods.getEmployeeUserId());

        WeChatTemplate weChatTemplate = new WeChatTemplate();

        ConfigMessage sysConfigMessage = configMessageService.selectConfigMessageByShopId(orderGoods.getShopId());

        // 设置模板id
        weChatTemplate.setTemplateId(sysConfigMessage.getWxOaOrderOvertimeId());

        //点击详情跳转的地址
        weChatTemplate.setUrl("");

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(orderGoods.getCreateTime());

        weChatTemplate.getData().put("thing12", WeChatTemplate.initData(customerUser.getNickName(),"#459ae9")); // 用户名称
        weChatTemplate.getData().put("amount4", WeChatTemplate.initData(orderGoods.getActualAmount().toString(),"#459ae9"));    // 订单金额
        weChatTemplate.getData().put("time3", WeChatTemplate.initData(dateStr,"#459ae9"));    // 下单时间
        weChatTemplate.getData().put("character_string1", WeChatTemplate.initData(orderNo,"#459ae9"));    // 订单号

        // 设置接收用户openId，这里填接收者的openid -- 店员(指定店员)
        if(employeeUser != null && employeeUser.getOpenId() != null && !employeeUser.getOpenId().equals("")){
            weChatTemplate.setToUser(employeeUser.getOpenId());
            messageCenter(weChatTemplate, orderGoods.getShopId());
        }
    }

    // 取消订单通知
    // 用户名称
    // {{thing9.DATA}}
    // 订单金额
    // {{amount23.DATA}}
    // 取消时间
    // {{time18.DATA}}
    // 取消原因
    // {{thing5.DATA}}
    // 订单号
    // {{character_string2.DATA}}
    public void messageOrderPayCancel(String orderNo, String cancelType){

        OrderGoods orderGoods = orderGoodsService.selectOrderGoodsByOrderNo(orderNo);

        CustomerUser customerUser = customerUserService.selectUserById(orderGoods.getOrderUserId());

        EmployeeUser employeeUser = employeeUserService.selectUserById(orderGoods.getEmployeeUserId());

        WeChatTemplate weChatTemplate = new WeChatTemplate();

        ConfigMessage sysConfigMessage = configMessageService.selectConfigMessageByShopId(orderGoods.getShopId());

        // 设置模板id
        weChatTemplate.setTemplateId(sysConfigMessage.getWxOaOrderCancelId());

        //点击详情跳转的地址
        weChatTemplate.setUrl("");

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sf.format(new Date());

        weChatTemplate.getData().put("thing9", WeChatTemplate.initData(customerUser.getNickName(),"#459ae9")); // 用户名称
        weChatTemplate.getData().put("amount23", WeChatTemplate.initData(orderGoods.getActualAmount().toString(),"#459ae9"));    // 订单金额
        weChatTemplate.getData().put("time18", WeChatTemplate.initData(dateStr,"#459ae9"));    // 取消时间
        weChatTemplate.getData().put("thing5", WeChatTemplate.initData(cancelType,"#459ae9"));    // 取消原因
        weChatTemplate.getData().put("character_string2", WeChatTemplate.initData(orderNo,"#459ae9"));    // 订单号

        // 设置接收用户openId，这里填接收者的openid -- 下单用户
        if(customerUser.getOpenId() != null && !customerUser.getOpenId().equals("")){
            weChatTemplate.setToUser(customerUser.getOpenId());
            messageCenter(weChatTemplate, orderGoods.getShopId());
        }

        // 设置接收用户openId，这里填接收者的openid -- 店员(指定店员)
        if(employeeUser != null && employeeUser.getOpenId() != null && !employeeUser.getOpenId().equals("")){
            weChatTemplate.setToUser(employeeUser.getOpenId());
            messageCenter(weChatTemplate, orderGoods.getShopId());
        }
    }



    // 消息中心
    public void messageCenter(WeChatTemplate weChatTemplate, String shopId)  {
        String wxAccessToken = getAccessToken(shopId);
        if(wxAccessToken != null){
            // 发送消息的接口
            String pust_message_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

            //调用微信接口，发送模板消息
            WeiXinResponse result = restTemplate.postForObject(String.format(pust_message_url, wxAccessToken),
                    weChatTemplate, WeiXinResponse.class);
            if (result.getErrcode() == 0){;
                System.out.println("==========微信发送消息发送成功==========");
            }else{
                System.out.println("==========微信发送消息发送失败，错误码：" + result.getErrcode() + "=========错误信息=========" + result.getErrmsg());
            }
        }else{
            System.out.println("==========微信发送消息失败:token为空");
        }
    }
    private String getCacheKey(String configKey)
    {
        return CacheConstants.THIRD_CONFIG + configKey;
    }
}
